import express from 'express';
import { getAccount } from '../../../middleWare/user/index.js';
import { addSql, deleteSql, getResult, listSql, multiDeleteSql } from '../../../util/operateSql.js';

var router = express.Router()
const table1 = 't_shopping_cart'
const table2 = 't_spu'
router.post('/delete',(req,res,next) => {
  const {ids}  = req.body
	
  const insertShoppingSql = multiDeleteSql(table1,{ids,logic: false})
	
  getResult(insertShoppingSql).then((result) => {
    res.json(req.app.locals.success('移除成功'))
  }).catch((err) => {
    
		res.json(req.app.locals.error(err))
  });
})
router.post('/add',getAccount,(req,res,next) => {
	const {merchant_id} = req.headers
  const {users_id,spu_id}  = req.body
  const insertShoppingSql = addSql(table1,{users_id,spu_id,merchant_id})
  getResult(insertShoppingSql).then((result) => {
    res.json(req.app.locals.success('新增成功'))
  }).catch((err) => {
    
    if (err.code == 'ER_DUP_ENTRY') {
      res.json(req.app.locals.error('请勿重复添加'))
    } else {
      res.json(req.app.locals.error(err))
    }
  });
})
router.get('/query',getAccount,async (req,res,next) => {
	const {merchant_id} = req.headers
  const {users_id}  = req.query
  const listShoppingSql = listSql(table1,{users_id,merchant_id})
  const shoppings = await getResult(listShoppingSql)
  const spuIds = shoppings.map(e => e.spu_id)
  const listSpuSql = listSql(table2,{id:spuIds,merchant_id,orderBy:'update_time'},{operate:{'in':['id']}})
	
  getResult(listSpuSql).then((result) => {
		result = result.map(e => {
			return {
				...e,
				shoppingId: shoppings.find(c => c.spu_id == e.id).id
			}
		})
    res.json(req.app.locals.success(result))
  }).catch((err) => {
    
    res.json(req.app.locals.error(err))
  });
})

export default router